package com.biomatch.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.biomatch.domain.DancePosition;
import com.biomatch.domain.Type;
import com.biomatch.dto.Pagination;
import com.biomatch.mapper.DanceTypeMappper;
import com.biomatch.service.DanceTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


@Service
@Transactional(rollbackFor = Exception.class)
public class DanceTypeServiceImpl implements DanceTypeService {

    @Autowired
    DanceTypeMappper danceTypeMappper;

    @Override
    public IPage<Type> getAllTypeByPage(Pagination pagination) {
        Page<Type> page = new Page<>(pagination.getCurrent(), pagination.getPageSize());
        return danceTypeMappper.selectPage(page, null);

    }

    @Override
    public List<Type> getAll() {
        return danceTypeMappper.selectList(null);
    }

    @Override
    public Type saveOrUpdate(Type type) {
        if (type.getId() <= 0) {
            QueryWrapper<Type> typeQueryWrapper = new QueryWrapper<>();
            typeQueryWrapper.eq("dancerTypeName",type.getDancerTypeName());
            if (danceTypeMappper.selectCount(typeQueryWrapper) > 0) {
                return null;
            }
            else {
                String code = String.valueOf(new Date().getTime());
                type.setDancerTypeId("T"+code);
                danceTypeMappper.insert(type);
                return type;
            }
        } else {
            QueryWrapper<Type> typeQueryWrapper = new QueryWrapper<>();
            typeQueryWrapper.eq("dancerTypeName",type.getDancerTypeName())
                    .ne("dancerTypeId",type.getDancerTypeId());
            if (danceTypeMappper.selectCount(typeQueryWrapper) > 0) {
                return null;
            }
            else {
                danceTypeMappper.updateById(type);
                return type;
            }
        }
    }

    @Override
    public Type delete(Type type) {
        QueryWrapper<Type> typeQueryWrapper = new QueryWrapper<>();
        typeQueryWrapper.eq("dancerTypeId",type.getDancerTypeId() );
        if (danceTypeMappper.selectCount(typeQueryWrapper) > 0) {
            danceTypeMappper.deleteById(type.getId());
            return type;
        } else
        {
            return null;
        }
    }
}
